package com.goldenautumn.prefabricate.utils

import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.activity.account.LoginActivity
import com.goldenautumn.prefabricate.activity.account.PhoneLoginActivity
import com.goldenautumn.prefabricate.activity.splash.ProtocolActivity
import com.goldenautumn.prefabricate.utils.Constants.IS_LOGIN
import com.goldenautumn.prefabricate.utils.Constants.LOGIN_TOKEN
import com.goldenautumn.prefabricate.utils.Constants.PROTOCOL_PRIVACY
import com.goldenautumn.prefabricate.utils.Constants.USER_ID
import qncx.external.common.constants.Intents
import qncx.external.common.room.RoomSql
import qncx.external.common.room.table.UserInfo
import qncx.external.common.utils.intent
import java.lang.reflect.Field
import java.math.RoundingMode
import java.text.DecimalFormat

fun getUserInfo(): UserInfo {
    var loginInfo = RoomSql.get()?.userInfoDao?.activeUserInfo
    return loginInfo ?: UserInfo()
}

fun isLogin(): Boolean {
    return SPUtils.getInstance().getBoolean(IS_LOGIN, false)
}

fun getUserID(): Long {
    return SPUtils.getInstance().getLong(USER_ID, 0L)
}

fun getToken(): String = SPUtils.getInstance().getString("LOGIN_TOKEN", "")

fun onCenterToast(msg: String): View {
    var activity = ActivityUtils.getTopActivity()
    var toast = Toast(activity)
    val view: View = LayoutInflater.from(activity).inflate(R.layout.layout_toast, null)
    view.findViewById<TextView>(R.id.tv_toast_message).text = "$msg"
    toast?.view = view
    toast?.setGravity(Gravity.CENTER, 0, 0)
    toast?.duration = Toast.LENGTH_SHORT
    toast.show()
    return view
}

fun goToStartActivity(intent: Intent, activity: FragmentActivity) {
    var type = intent.getStringExtra(Intents.START_ACTIVITY_TYPE)
    var params = intent.getStringExtra(Intents.START_ACTIVITY_PARAMS)
    if (type == "Agreement")
        activity.startActivity(ProtocolActivity::class.intent.putExtra(PROTOCOL_PRIVACY, params))
}

fun numberFormat(num: String, roundingMode: RoundingMode = RoundingMode.HALF_EVEN): String {
    var dec = DecimalFormat("#,##0.00")
    dec.roundingMode = roundingMode
    return dec.format(num.toDouble())
}

fun priceZero(price: String): String {
    if (!price.contains(".")) return price
    var number = price.substring(price.indexOf(".") + 1, price.length)
    var num = price.substring(0, price.indexOf("."))
    if (number.toLong() == 0L) return num
    return price
}

fun Any.objectToMap(): HashMap<String, Any> {
    val map: HashMap<String, Any> = HashMap()
    return try {
        val declaredFields: Array<Field> = javaClass.declaredFields
        for (field in declaredFields) {
            field.isAccessible = true
            if (this != null) map[field.name] = field.get(this)
        }
        map
    } catch (e: NullPointerException) {
        map
    }

}

fun View.clickIsLogin(action: (view: View) -> Unit) {
    setOnClickListener {
        if (!isLogin()) {
            var activity = ActivityUtils.getTopActivity() as FragmentActivity
            activity.startActivity(LoginActivity::class.intent)
        } else action(it)
    }
}

fun ImageView.loadImgUrl(imgPath: String?, roundingRadius: Int = 1) {
    try {
        imgPath?.let {
            if (it.isNotBlank()) {
                Glide.with(this)
                    .asBitmap()
                    .load(imgPath)
                    .transform(CenterCrop(), RoundedCorners(roundingRadius))
//                .diskCacheStrategy(cache)
                    .placeholder(ContextCompat.getDrawable(this.context, R.mipmap.ic_img_occupancy))
                    .error(ContextCompat.getDrawable(this.context, R.mipmap.ic_img_occupancy))
                    .dontAnimate()
                    .into(this)
//                    .into(object : CustomTarget<Bitmap>() {
//
//                        override fun onLoadCleared(placeholder: Drawable?) {
//
//                        }
//
//                        override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
//                            this@loadImgUrl.setImageBitmap(resource)
//                        }
//                    })

            }

        }
    } catch (e: Exception) {
        LogUtils.d(e)
    }
}

fun imageBackground(): Drawable {
    var colorsArr = arrayListOf(
        "#A3A6B9",
        "#C8BC98",
        "#BDABA9",
        "#DBBFB2",
        "#B1C5A3",
        "#AF9AB2",
        "#8FA3A7",
        "#B6ADAD"
    )
    //边框颜色int fillColor = Color.parseColor("#DFDFE0")
    var position = (0..7).random()
    // 内部填充颜色
    var startColor = Color.parseColor(colorsArr[position])
    val endColor: Int = Color.parseColor(colorsArr[position])
    val colors = intArrayOf(startColor, endColor) //分别为开始颜色，中间夜色，结束颜色
    val gd = GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, colors)
    return gd
}

fun onLogout() {
    SPUtils.getInstance().put("IS_LOGIN", false)
    SPUtils.getInstance().put("LOGIN_TOKEN", "")
    SPUtils.getInstance().put("USER_ID", "")
    SPUtils.getInstance().remove(IS_LOGIN)
    SPUtils.getInstance().remove(LOGIN_TOKEN)
    SPUtils.getInstance().remove(USER_ID)
    var dao = RoomSql.get()?.userInfoDao
    var userInfo = dao?.activeUserInfo
    userInfo?.active = false
    userInfo?.let { dao?.updateUserInfo(userInfo) }
}